package 反射和内省;

import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.UUID;

/**
 * Created by Administrator on 2017/8/13.
 */
public class MyBeanUtils {
    /**
     *
     * @param object 存放封装数据的那个类
     * @param map    key为请求参数名,value为请求参数名对应的值(可能有多个值)
     */
    public static void populate(Object object, Map<String,String[]> map) throws IntrospectionException, InvocationTargetException, IllegalAccessException {
        //1、获得BeanInfo对象
        BeanInfo beanInfo = Introspector.getBeanInfo(Object.class);
        //2、得到封装类的字段对象
        PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
        //3、遍历字段对象的名字，看是否和key有匹配的
        for (PropertyDescriptor p : propertyDescriptors) {
            if (map.containsKey(p.getName())){
                Method setMethod = p.getWriteMethod(); //即得到对应属性的setXxx方法
                setMethod.invoke(object,map.get(p.getName()));
            }
        }
    }
}
